<template>
  <NSelect
    :key="'page_id'"
    :options="list"
    label-field="page_name"
    :value-field="getProps.isUrl ? 'preview_url' : 'page_id'"
  />
</template>

<script setup lang="ts">
  import { useRoute } from 'vue-router'
  const route = useRoute()
  import { NSelect } from 'naive-ui'
  import { computed, reactive, ref, watch } from 'vue'
  import { useStore } from '@/store'
  const store = useStore()
  const emit = defineEmits(['update:pid'])
  const props = defineProps({
    pid: {
      type: [String, Number],
      default: ''
    },
    isUrl: {
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: true
    }
  })
  const getProps = reactive(props)
  const list = computed(() => {
    return store.state.intelligent.pageList
  })
  const isEdit = computed(() => {
    return !!store.state.intelligent.data.id
  })
  const pageId = ref()
  if (getProps.required) {
    list.value.unshift({
      page_name: '请选择',
      preview_url: null,
      page_id: null
    })
  }
  watch(
    () => list.value,
    (val) => {
      if (!val || !val.length || isEdit.value) {
        return false
      }
      const id = getProps.isUrl ? val[0].preview_url : val[0].page_id
      if (getProps.required) {
        pageId.value = String(id)
        onChange(id)
      }
    },
    {
      immediate: true
    }
  )
  watch(
    () => getProps.pid,
    (val) => {
      pageId.value = val ? String(val) : val
    },
    {
      immediate: true
    }
  )
  function onChange(val: any) {
    emit('update:pid', val)
  }
</script>

<style scoped lang="scss"></style>
